<template>
    <el-container>
        <vHeadSpace/>
        <el-container>
            <vAsideSpace/>
            <el-container>
                <el-main class="main">
                    <div class="content">
                        <div class="block">
                            <el-date-picker
                                    v-model="value1"
                                    type="datetimerange"
                                    :picker-options="pickerOptions"
                                    @change="selectchange()"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :default-time="[this.default_date1, this.default_date2]">
                            </el-date-picker>
                            <label style="font-weight: normal;font-size:14px">在线设备:</label>
                            <el-select v-model="hostIds" clearable placeholder="在线设备" @change="selectchange()">
                                <el-option
                                        v-for="item in online_host_list"
                                        :key="item.hostid"
                                        :label="item.host"
                                        :value="item.hostid">
                                </el-option>
                            </el-select>
                            <el-button type="primary" size="small" style="margin-left:5px" @click="exportClick()">
                                导出性能数据
                            </el-button>
                        </div>
                        <!--                        <div class="lineStyle">-->
                        <!--                            <div id="lineMin"></div>-->
                        <!--                        </div>-->

                        <div v-loading="isloading" style="margin-top: 30px;">
                            <div id="charts" class="chart-con"></div>
                        </div>
                    </div>
                </el-main>
                <vFootSpace/>
            </el-container>
        </el-container>
    </el-container>
</template>

<script>
    import axios from 'axios'
    import * as echarts from 'echarts';

    export default {
        name: 'PerformanceExcel',
        data() {
            return {
                value1: [],
                titleName: '',
                echarts: '',
                hostIds: '',
                host: '',
                name: '',
                status: '',
                online_host_list: [],
                data1_min: [],
                data2_min: [],
                data1_avg: [],
                data2_avg: [],
                data1_max: [],
                data2_max: [],
                ratio: 100,
                default_date1: '',
                default_date2: '',
                data_zoom_self: {
                    show: true,
                    realtime: true,
                    start: 0,
                    end: this.ratio,
                    type: 'slider',
                },
                isloading: false,
                pickerOptions: {
                    disabledDate(time) {
                        const start = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
                        return time.getTime() >= start;
                    },
                },
            }
        },
        methods: {
            getPerformanceInfo(hostid, startTime, endTime) {
                let d1 = new Date();
                if (!hostid) {
                    this.hostIds = this.online_host_list[0].hostid;
                }
                if (!endTime) {
                    endTime = `${d1.getFullYear()}-${d1.getMonth() + 1}-${d1.getDate()} ${d1.getHours()}:${d1.getMinutes()}:${d1.getSeconds()}`;
                    this.value1.unshift(endTime);
                    this.default_date2 = endTime;
                }
                d1.setDate(d1.getDate() - 1)
                if (!startTime) {
                    startTime = `${d1.getFullYear()}-${d1.getMonth() + 1}-${d1.getDate()} ${d1.getHours()}:${d1.getMinutes()}:${d1.getSeconds()}`;
                    this.value1.unshift(startTime);
                    this.default_date1 = startTime;
                }
                axios({
                    method: "post",
                    url: 'report/performance_info.action',
                    data: {
                        hostid: this.hostIds,
                        startTime: this.value1[0],
                        endTime: this.value1[1]
                    }
                }).then((res) => {
                    for (let i = 0; i < res.data.content.result.length; i++) {
                        // console.log(res.data.content.result)
                        this.initParams();
                        let _this = this;
                        let chartDiv = document.getElementById('charts');
                        let flowChart = document.createElement('div');
                        flowChart.id = "name" + i;
                        flowChart.style.width = "90%"
                        flowChart.style.height = "400px";
                        flowChart.style.margin = "20px auto"
                        flowChart.style.backgroundColor = 'white'
                        chartDiv.appendChild(flowChart);
                        this.titleName = res.data.content.result[i][0];
                        for (let j = 1; j < res.data.content.result[i].length; j++) {

                            this.data1_min.push(res.data.content.result[i][j][0])
                            this.data2_min.push(res.data.content.result[i][j][1])

                            this.data1_avg.push(res.data.content.result[i][j][0])
                            this.data2_avg.push(res.data.content.result[i][j][2])

                            this.data1_max.push(res.data.content.result[i][j][0])
                            this.data2_max.push(res.data.content.result[i][j][3])

                        }
                        this.drawLine("name" + i);
                    }
                }).finally(()=>{
                    this.isloading = false;
                })
            },

            initParams() {
                this.titleName = '';
                this.data1_min = [];
                this.data2_min = [];
                this.data1_avg = [];
                this.data2_avg = [];
                this.data1_max = [];
                this.data2_max = [];
            },

            selectchange() {
                if (this.value1.length != 0 && this.hostIds != "")
                    this.showCharts();
            },

            showCharts() {
                let hostids = this.hostIds;
                this.isloading = true;
                let id = document.getElementById('charts');
                let childNodes = id.childNodes;

                while (childNodes.length > 0) {
                    id.removeChild(childNodes[childNodes.length - 1]);
                }
                var startDate = Date.parse(this.value1[0]);
                var endDate = Date.parse(this.value1[1]);
                var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
                this.data_zoom_self.end = 100 / days;
                this.getPerformanceInfo(hostids, this.value1[0], this.value1[1])
            },

                    drawLine(chartDate) {
                let chartName = chartDate;
                // let  myChart = this.$echarts.init(this.$refs.chartName)
                let chartDom = document.getElementById(chartName);
                let myChart = echarts.init(chartDom);

                let option = {
                    dataZoom: this.data_zoom_self,
                    title: {
                        text: this.titleName,
                        // backgroundColor: 'rgb(220,226,235)'
                         // left: ''
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['min', 'avg', 'max']
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 90
                    },
                    grid: {
                        top: '5%',
                        left: '15%',
                        right: '15%',
                        bottom: '5%',
                        containLabel: true
                    },

                    xAxis: {
                        show: false,
                        type: 'category',
                        boundaryGap: false,
                        data: this.data1_min,
                        axisLabel: {
                            interval: 0,
                            rotate: 40
                        }
                    },
                    yAxis: {
                        type: 'value'

                    },
                    series: [
                        {
                            name: 'min',
                            type: 'line',
                            data: this.data2_min
                        },
                        {
                            name: 'avg',
                            type: 'line',
                            data: this.data2_avg
                        },
                        {
                            name: 'max',
                            type: 'line',
                            data: this.data2_max
                        }
                    ]
                };
                option && myChart.setOption(option);
            },

            //最小趋势折线图
            drawEcharts() {
                let chartDom = document.getElementById('lineMin');
                let myChart = echarts.init(chartDom);
                let option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['min', 'avg', 'max']
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 90
                    },
                    grid: {
                        top: '5%',
                        left: '15%',
                        right: '15%',
                        bottom: '5%',
                        containLabel: true
                    },

                    xAxis: {
                        show: false,
                        type: 'category',
                        boundaryGap: false,
                        data: this.data1_min,
                        axisLabel: {
                            interval: 0,
                            rotate: 40
                        }
                    },
                    yAxis: {
                        type: 'value'

                    },
                    series: [
                        {
                            name: 'min',
                            type: 'line',
                            data: this.data2_min
                        },
                        {
                            name: 'avg',
                            type: 'line',
                            data: this.data2_avg
                        },
                        {
                            name: 'max',
                            type: 'line',
                            data: this.data2_max
                        }
                    ]
                };
                option && myChart.setOption(option);
                return myChart;
            },

            // 导出
            exportClick() {
                if (this.hostIds === "") return this.$message.error("请选择设备");
                if (this.value1.length === 0) return this.$message.error("请选择时间");
                let dateNow = new Date();
                let st = new Date(this.value1[0]);
                if (dateNow.getTime() < st.getTime()) {
                    return this.$message.error("开始时间不得大于当前时间")
                }
                this.$confirm('此操作将导出该条件下的所有数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios({
                        method: "post",
                        url: '/report/export_performance_excel.action',
                        data: {
                            hostid: this.hostIds.toString(),
                            startTime: this.value1[0],
                            endTime: this.value1[1]
                        },
                        crossOrigin: true,
                        crossDomain: true,
                        responseType: 'blob',
                    }).then((response) => {
                        const link = document.createElement('a')
                        let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'})
                        link.style.display = 'none'
                        link.href = URL.createObjectURL(blob)
                        let fileName = "性能分析报表"
                        link.download = fileName
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }).catch((error) => {
                        console.log(error);
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消导出'
                    });
                });
            },

            // 获取主机列表
            async getHostList() {
                let _this = this;
                _this.tohost = this.$route.params.host
                let response = await axios({
                    method: 'get',
                    url: '/report/get_all_online_host.action'
                })
                this.online_host_list = response.data.content.result
            },
        },
        mounted() {
            // this.drawEcharts();
            // this.default_date = new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getSeconds()
            this.getHostList().then(() => {
                this.isloading = true
                this.getPerformanceInfo()
            })
        }
    }
</script>
<style scoped>
    .main {
        height: 88vh;
        width: 100%;
        margin-top: 60px;
        padding: 10px;
    }

    .outcontainer_right {
        height: 100%;
        overflow-x: hidden
    }

    .content {
        margin-top: 0;
        width: 100%;
        height: 97%;
        overflow-x: hidden
    }

    .itemInfo-middle-type div {
        display: inline;
        padding-left: 5px;
        padding-right: 5px;
        height: 30px;
        line-height: 50px;
        color: #d9d9d9;
        border-top: 1px solid #d9d9d9;
        border-left: 1px solid #d9d9d9;
        border-bottom: 1px solid #d9d9d9;
    }

    #lineMin {
        width: 80%;
        height: 400px;
        float: left
    }

    .chart-con {
        /*margin: 20px auto;*/
    }
</style>
